package com.egame.manage.biz.web.controller.op;

import java.awt.image.BufferedImage;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.egame.common.servlet.WebUtils;
import cn.egame.common.util.Utils;
import cn.egame.ext.op.AdvDetail;
import cn.egame.interfaces.ConstVar;
import cn.egame.interfaces.fl.FileInfo;
import cn.egame.interfaces.fl.FileUsedType;
import cn.egame.interfaces.fl.FileUtils;

import com.egame.manage.biz.server.ManageClient;
import com.egame.manage.biz.server.ManageClientExt;
import com.egame.manage.biz.server.gc.GameServiceImpl;
import com.egame.manage.biz.server.op.OperationActivityServiceImpl;
import com.egame.manage.biz.server.op.StoreAdvertiseServiceImpl;
import com.egame.manage.biz.utils.ConstantVar;
import com.egame.manage.biz.web.controller.BaseController;
import com.lenovo.manager.business.domain.UserBean;

@Controller
@RequestMapping("/store/game")
public class GameActivityController extends BaseController {

	public GameActivityController(){		
	}
	public GameActivityController(HttpServletRequest req, HttpServletResponse resp) {
		super(req, resp);
	}
	
	//列表
		@RequestMapping(value = "/advertise/list", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView listGameAdvertise(HttpServletRequest req, HttpServletResponse resp) throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}	
			int recordTypeNum = WebUtils.getInt(req,"recordTypeNum",0);
			AdvDetail bean = new AdvDetail();
			String banner = WebUtils.getString(req, "banner","");
			String beginTime = WebUtils.getString(req, "beginTime","");
			String endTime = WebUtils.getString(req, "endTime","");
			bean.setTitle(banner);
			bean.setBeginString(beginTime);
			bean.setEndString(endTime);
			if(""!=beginTime){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date beginDate = sdf.parse(beginTime);
				bean.setBeginTime(beginDate);
			}
			if(""!=endTime){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date endDate = sdf.parse(endTime);
				bean.setEndTime(endDate);
			}
			bean.setStatus(1);//开启状态
			List<AdvDetail> advHomeList1 = new ArrayList<AdvDetail>();
			List<AdvDetail> advHomeList2 = new ArrayList<AdvDetail>();
			List<AdvDetail> advHomeListFirst = new ArrayList<AdvDetail>();
			List<AdvDetail> advHomeListSecond = new ArrayList<AdvDetail>();
			List<AdvDetail> advHomeListThird = new ArrayList<AdvDetail>();
			List<AdvDetail> advHomeList3 = new ArrayList<AdvDetail>();
			if(recordTypeNum == 0 ||recordTypeNum ==ConstantVar.STORE_MENU_GAME_LOOP){
				bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_LOOP);
				//循环广告位
				advHomeList1 = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			}
			advHomeList1 = checkAdvertiseValid(advHomeList1);
			if(recordTypeNum == 0 ||recordTypeNum ==ConstantVar.STORE_MENU_GAME_DOUBLE){
				//双屏广告位
				bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_DOUBLE);
				advHomeListFirst = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			}
			if(recordTypeNum == 0 ||recordTypeNum ==ConstantVar.STORE_MENU_GAME_DOUBLE_FIRST){
				//双屏广告位
				bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_DOUBLE_FIRST);
				advHomeListSecond = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			}
			if(recordTypeNum == 0 ||recordTypeNum ==ConstantVar.STORE_MENU_GAME_DOUBLE_SECOND){
				//双屏广告位
				bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_DOUBLE_SECOND);
				advHomeListThird = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			}
			advHomeList2.addAll(advHomeListFirst);
			advHomeList2.addAll(advHomeListSecond);
			advHomeList2.addAll(advHomeListThird);
			advHomeList2 = checkAdvertiseValid(advHomeList2);
			if(recordTypeNum == 0 ||recordTypeNum ==ConstantVar.STORE_MENU_GAME_ONE){
				//单屏广告位
				bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_ONE);
				advHomeList3 = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			}
			advHomeList3 = checkAdvertiseValid(advHomeList3);
			ModelAndView mv = new ModelAndView("/new/op/store/gameAdvertiseList");	
			mv.addObject("advHomeList1", advHomeList1);
			mv.addObject("advHomeList2", advHomeList2);
			mv.addObject("advHomeList3", advHomeList3);
			mv.addObject("banner", banner);
			mv.addObject("beginTime", beginTime);
			mv.addObject("endTime", endTime);
			mv.addObject("recordTypeNum", recordTypeNum);
			return mv;
		}
		//新增跳转
		@RequestMapping(value = "/advertise/set/show", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView showNewAdvertisement(HttpServletRequest req, HttpServletResponse resp)throws Exception{
			return new ModelAndView("/new/op/store/newGameAdvertise");
		}	
		//新增提交
		@RequestMapping(value = "/advertise/new", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView newAdv(HttpServletRequest req, HttpServletResponse resp,AdvDetail bean,String beginAdv,String endAdv) throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}	
			try{							
				bean.setBeginTime(Utils.parseDate(bean.getBeginString()));
				bean.setEndTime(Utils.parseDate(bean.getEndString()));					
			}catch(Exception e){
				bean.setBeginTime(new Date());
				bean.setEndTime(new Date());
			}	
			bean.setOperationId((int) loginUserId);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date beginTime = sdf.parse(beginAdv);
			Date endTime = sdf.parse(endAdv);
			bean.setBeginTime(beginTime);
			bean.setEndTime(endTime);
			bean.setStatus(1);
			bean.setRecordType(1);
			int maxSortNo = StoreAdvertiseServiceImpl.getInstance().getMaxSortNo(bean.getRecordType(), bean.getPositionTypeId());
			bean.setSortNo(1 + maxSortNo);	
			bean.setInsertTime(new Date());
			//TODO
			//设置bean值(position_id)
			bean.setRecordType(1);//活动
			ManageClientExt.getInstance().addAdvDetail(appId, loginUserId, bean);
			return listGameAdvertise(req, resp);
		}
		//删除
		@RequestMapping(value = "/advertise/delete", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView deleteAdvertisement(HttpServletRequest req, HttpServletResponse resp)throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}
			int advertiseId = WebUtils.getInt(req,"id",0);	
			//可用做提示框验证条件
			int deleteId = StoreAdvertiseServiceImpl.getInstance().deleteAdvertisement(appId, loginUserId, advertiseId);
			return listGameAdvertise(req, resp);
		}
		//编辑跳转
		@RequestMapping(value = "/advertise/edit/show", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView editHomeAdvertisement(HttpServletRequest req, HttpServletResponse resp)throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}
			int advertiseId = WebUtils.getInt(req,"id",0);	
			AdvDetail bean = ManageClientExt.getInstance().getAdvDetailById(appId, loginUserId, advertiseId);		
			ModelAndView mv = new ModelAndView("/new/op/store/editGameAdvertise"); 
			//TODO
			//文件路径
			FileInfo file = ManageClient.getInstance().getFileInfo(appId, loginUserId, bean.getEfsId());
			if(file == null) file = new FileInfo();
			//后期要修改
			String filepath =ConstVar.DOWNLOAD_URL + FileUtils.getFilePath(FileUsedType.adver_photo, bean.getEfsId(), file.getFileName());
			mv.addObject("bean", bean);
			mv.addObject("filepath", filepath);
			return mv;
		}
		//编辑提交
		@RequestMapping(value = "/advertise/set/edit", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView setHXAdvertisement(AdvDetail bean,HttpServletRequest req, HttpServletResponse resp)throws Exception{

			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}
			try{							
				bean.setBeginTime(Utils.parseDate(bean.getBeginString()));
				bean.setEndTime(Utils.parseDate(bean.getEndString()));					
			}catch(Exception e){
				bean.setBeginTime(new Date());
				bean.setEndTime(new Date());
			}	
			
			int maxSortNo = StoreAdvertiseServiceImpl.getInstance().getMaxSortNo(bean.getRecordType(), bean.getPositionTypeId());
			bean.setSortNo(1 + maxSortNo);	
			bean.setInsertTime(new Date());		
			ManageClientExt.getInstance().updateAdvDetail(appId, loginUserId, bean);
			return listGameAdvertise(req, resp);
		}
		//历史数据
		@RequestMapping(value = "/advertise/history/list", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView listHXHistoryActivity(HttpServletRequest req, HttpServletResponse resp) throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}
			ModelAndView mv = new ModelAndView("/new/op/store/gameHisAdvertise");
			List<AdvDetail> advHomeList1 = null;
			List<AdvDetail> advHomeList2 = null;
			List<AdvDetail> advHomeList3 = null;
			AdvDetail bean = new AdvDetail();
			bean.setStatus(0);//关闭状态
			bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_LOOP);
			advHomeList1 = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			List<AdvDetail> expiredList1 = this.getExpiredList(ConstantVar.STORE_MENU_GAME_LOOP);
			advHomeList1.addAll(expiredList1);
			bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_DOUBLE);
			advHomeList2 = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			List<AdvDetail> expiredList2 = this.getExpiredList(ConstantVar.STORE_MENU_GAME_DOUBLE);
			advHomeList2.addAll(expiredList2);
			bean.setPositionTypeId(ConstantVar.STORE_MENU_GAME_ONE);
			advHomeList3 = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean); 
			List<AdvDetail> expiredList3 = this.getExpiredList(ConstantVar.STORE_MENU_GAME_ONE);
			advHomeList3.addAll(expiredList3);
			mv.addObject("advHomeList1", advHomeList1);
			mv.addObject("advHomeList2", advHomeList2);
			mv.addObject("advHomeList3", advHomeList3);
			
			return mv;
		}
		//上移
		@RequestMapping(value = "/advertise/upper", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView upperSortNo(HttpServletRequest req, HttpServletResponse resp)throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}
			int advertiseId = WebUtils.getInt(req,"id",0);
			OperationActivityServiceImpl.getInstance().upper(appId, loginUserId, advertiseId);		
			return listGameAdvertise(req,resp);
		}	
		//下移
		@RequestMapping(value = "/advertise/lower", method = {RequestMethod.GET,RequestMethod.POST})
		public ModelAndView lowerSortNo(HttpServletRequest req, HttpServletResponse resp)throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}
			int advertiseId = WebUtils.getInt(req,"id",0);
			OperationActivityServiceImpl.getInstance().lower(appId, loginUserId, advertiseId);
			return listGameAdvertise(req,resp);
		}
		
		@ResponseBody
		@RequestMapping(value = "/image/width/height", method = {RequestMethod.GET,RequestMethod.POST})
		public String isFitImage(String name,int width,int height,int type,HttpServletRequest req, HttpServletResponse resp)throws Exception{
			if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
				UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
				loginUserId = userBean.getOperatorId();
			}
			resp.setContentType("text/plain; charset=UTF-8");
			MultipartFile file = ((MultipartHttpServletRequest)req).getFile(name);			
			BufferedImage bf = null;
			if(file != null){
				bf = ImageIO.read(file.getInputStream());
			}		
			if(bf != null){
				if(bf.getWidth() == width && bf.getHeight() == height){
					if(file != null){
						long efsid = ManageClient.getInstance().writeToFile(file.getInputStream(),type,appId,loginUserId,file.getOriginalFilename());	
						if(efsid>0){
							return "" + efsid + "," +GameServiceImpl.getInstance().getImagePath(appId, loginUserId, efsid);
						}
					}	
				}			
			}		
			return "-1,-1"; 
		}

		public List<AdvDetail> checkAdvertiseValid(List<AdvDetail> validList) {
			List<AdvDetail> tempList = new ArrayList<AdvDetail>();
			if(validList != null &&validList.size() != 0){
				for(AdvDetail ad : validList) {
					if(ad.getEndTime().getTime()>System.currentTimeMillis()){
						tempList.add(ad);
					}
				}
			}
			return tempList;
		}
		
		public List<AdvDetail> getExpiredList(int positionType){
			List<AdvDetail> tempList = new ArrayList<AdvDetail>();
			List<AdvDetail> expiredList = new ArrayList<AdvDetail>();
			AdvDetail bean = new AdvDetail();
			bean.setStatus(1);
			bean.setPositionTypeId(positionType);
			try {
				tempList = ManageClientExt.getInstance().listAdvDetailByBean(appId,loginUserId,bean);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			for(AdvDetail ad : tempList){
				if(ad.getEndTime().getTime()<System.currentTimeMillis()){
					expiredList.add(ad);
				}
			}
			return expiredList;
		}
}
